package main

import (
	"dmsv/common"
	"dmsv/ivr"
	"dmsv/models"
	"dmsv/process"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"strings"
	"time"
)

const (
	Monday    = "MON"
	TuesDay   = "TUES"
	Wednesday = "WED"
	Thurthday = "THUR"
	Friday    = "FRI"
	Satday    = "SAT"
	Sunday    = "SUN"
)

func timeSplite(timeStr string) (result []process.IvrTimeActive) {

	if len(timeStr) == 0 {
		active := process.IvrTimeActive{}
		active.ActiveFrom, _ = time.ParseInLocation("15:04", "00:00", time.Local)
		active.ActiveEnd, _ = time.ParseInLocation("15:04", "23:59", time.Local)
		result = append(result, active)
		return
	}
	//00:00-03:00/04:30-06:00
	times := strings.Split(timeStr, "/")
	for _, ts := range times {

		t := strings.Split(ts, "-")

		if len(t) != 2 {
			return
		}
		active := process.IvrTimeActive{}
		active.ActiveFrom, _ = time.ParseInLocation("15:04", t[0], time.Local)

		active.ActiveEnd, _ = time.ParseInLocation("15:04", t[1], time.Local)
		result = append(result, active)
	}

	return
}

func Reload() {

	//企业信息加载
	for count := 0; ; count++ {

		res, err := models.LoadCompany(10, count)
		if err != nil {
			break
		}

		logs.Debug("读取企业数量:%v.", len(res))
		for _, c := range res {

			logs.Debug("加载企业【 %v 】相关信息...", c.AppId)
			h, err := process.AddNewEnterprice(c.AppId, c.NavAudio, c.Number, c.Acd, c.GetKey)
			if err != nil {
				logs.Error("加载失败:%v err:%v", c.AppId, err)
				continue
			}

			//基础语音
			bv, err := models.LoadBasicVoice(c.AppId)
			if err != nil {
				logs.Error("[%v]基础语音加载失败:%v", c.AppId, err)
			} else {
				leaveMsg := "false"
				if bv.LeaveSwitch {
					leaveMsg = "true"
				}
				h.SetWaitInfo(bv.WaitVoice, bv.EndVoice, leaveMsg, bv.PlayTimes, bv.StopSecond)
				h.SetOffWorkVoice(bv.OffWorkVoice, bv.LeaveVoice, bv.BOffWorkLeave)
				h.SetPlayServiceId(bv.PlayServiceId)
			}

			//满意度配置加载
			h.SatisfactionConfig(c.Satisfaction, c.SatisfactionAuto, c.SatisfactionTip, c.EndVoice)
			//基础设置
			h.LoadCompanyBasic(c.BasicConf)

			result, err := models.ReloadNumberForCompany(c.AppId)

			for _, number := range result {

				logs.Debug("加载企业 [%v] 号码:%12v;呼入属性:%v,呼出属性:%v", c.AppId, number.FixedNumber, number.CallIn, number.Display)
				if number.CallIn == 1 {
					h.ListenNumber(number.FixedNumber)
					transferType, arg, err := models.GetTransferInfo(number.FixedNumber)
					if err != nil {
						logs.Error("加载号码[%v]呼入配置失败：%v", number.FixedNumber, err)
					} else {
						h.SetTransfer(number.FixedNumber, transferType, arg)
					}
				}

				if number.Display == 1 {
					h.AddDisplay(number.FixedNumber)
				}
			}

			logs.Debug("加载企业 [%v] 队列信息;", c.AppId)
			for offset := 0; ; offset++ {

				//加载队列
				ques, err := models.LoadQueue(c.AppId, offset)
				if err != nil {
					break
				}

				for _, q := range ques {
					logs.Debug("[%v]加载队列Id[%v],队列名称[%v],分发模式[%v].", q.AppId, q.Id, q.Name, q.DistribWay)
					r := process.AddNewQue(q.AppId, q.Name, q.KeyIn, q.Media, q.DistribWay, q.Id)
					if !r {
						logs.Error("recover err:%v", q)
					}
				}
			}

			//加载ivr
			ivrs, err := models.LoadIvrMange(c.AppId)
			if err != nil {
				if err.Error() == "EOF" {
					continue
				} else {
					logs.Error("appId [%v] 加载ivr流程节点失败:%v", c.AppId, err.Error())
					break
				}
			}

			//加载企业ivr
			for _, i := range ivrs {

				handle := ivr.InitHandle(c.AppId, i.Id)
				if handle == nil {
					logs.Error("appId:%v ,ivr Id 初始化失败.", c.AppId, i.Id)
					continue
				}

				//关联ivr号码
				/*
					number := ""
					if i.Number != nil {
						number = i.Number.FixedNumber
					}
				*/
				activeTime := timeSplite(i.Time)
				activeDay := common.WeekParse(i.Week)

				ivrId := fmt.Sprintf("%d", i.Id)
				h.AddNewIvrManage(ivrId, i.Name, i.Number, *handle, activeTime, activeDay)
			}
		}
	}

	//加载坐席签入信息
	for i := 0; ; i++ {

		signInInfo, err := models.LoadSignIn(i)
		logs.Debug("加载坐席签入信息数量 [%v]", len(signInInfo))
		if err != nil {
			if !strings.HasPrefix(err.Error(), "EOF") {
				logs.Error("加载坐席签入信息 失败:%v", err)
			}

			break
		}

		for _, s := range signInInfo {
			queId := fmt.Sprintf("%d", s.Que.Id)
			err = process.ServiceSignIn(s.AppId, queId, s.Number, s.ServiceId, s.Display)
			if err == nil {
				logs.Debug("load company[%v] service[%v]sign in queId:[%v] quename[%v] ",
					s.AppId, s.ServiceId, queId, s.Que.Name)
			} else {
				logs.Error("recover err:%v,%v", err, *s)
			}
		}
	}
}
